<?php
namespace app\traits;

use app\helper\Hierarchy as Helper;

/*
 * 树形结构类
 *
 */

trait Hierarchy
{
    use Cache;
    // static $props = ['value' => 'id', 'label' => 'name', 'pid' => 'pid'];
    /**
     * 树形数据
     *
     * @param boolean $set
     * @param integer $pid
     * @return void
     */
    public static function tree(array $props = ['value' => 'id', 'label' => 'name', 'pid' => 'pid'], int $level = 5, array $where = []) {
        $key = self::getCacheKey('Tree');
        // $tree = cache($key);
        // if($tree === false || $tree === null){
            $list = self::where($where)->select()->toArray();
            Helper::init($list, $props);
            $tree = Helper::tree(0, $level);
            cache($key, $tree, 3600 * 24 * 7);
        // }
        return $tree;
    }
    /**
     * 表格数据
     *
     * @param boolean $set
     * @param integer $pid
     * @return void
     */
    public static function table(array $props = [], int $level = 5, array $where = [])
    {
        $key = self::getCacheKey('Table');
        $table = cache($key);
        if($table === false || $table === null){
            $list = self::wehre($where)->select()->toArray();
            Helper::init($list, $props);
            $table = Helper::table(0, $level);
            cache($key, $table, 3600 * 24 * 7);    
        }
        return $table;
    }
    /*
     * 获取数据树子ID
     * @param int $id 起始ID
     * @return array
     */
    public static function cids(int $id = 0)
    {
        return Helper::cids(self::list(), $id);
    }
    /*
     * 获取所有父级ID
     */
    public static function pids(int $id = 0){
        return Helper::pids(self::list(), $id);
    }
    /*
     * 获取所有父级label
     */
    public static function labels(int $id = 0, $props = []){
        $props += ['value' => 'id', 'label' => 'title', 'pid' => 'pid'];
        $list = self::list($props['value']);
        $label = $list[$id][$props['label']];
        if (isset($list[$id][$props['pid']]) && $list[$id][$props['pid']] != 0) {
            $label = self::labels($list[$id][$props['pid']], $props) . $label;
        }
        return $label;
    }
}
